<template>
  <div class="following-page">
    <div class="page-header">
      <h2>我的关注</h2>
      <div class="header-actions">
        <el-input
            v-model="searchKeyword"
            placeholder="搜索关注用户..."
            prefix-icon="Search"
            clearable
            class="search-input"
        />
        <el-button type="primary" @click="showRecommendation = true">
          <el-icon><UserAdd /></el-icon>
          发现更多UP主
        </el-button>
      </div>
    </div>

    <div class="following-content">
      <!-- 标签页 -->
      <el-tabs v-model="activeTab" class="following-tabs">
        <el-tab-pane label="全部关注" name="all">
          <FollowingList
              :users="filteredFollowing"
              :loading="loading"
              @unfollow="handleUnfollow"
          />
        </el-tab-pane>
        <el-tab-pane label="互相关注" name="mutual">
          <FollowingList
              :users="mutualFollowing"
              :loading="loading"
              @unfollow="handleUnfollow"
          />
        </el-tab-pane>
        <el-tab-pane label="特别关心" name="special">
          <FollowingList
              :users="specialFollowing"
              :loading="loading"
              @unfollow="handleUnfollow"
          />
        </el-tab-pane>
      </el-tabs>

      <!-- 分页 -->
      <div v-if="filteredFollowing.length > 0" class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="filteredFollowing.length"
            :page-sizes="[20, 40, 60, 80]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 推荐关注弹窗 -->
    <el-dialog
        v-model="showRecommendation"
        title="发现更多UP主"
        width="600px"
        class="recommendation-dialog"
    >
      <RecommendationList @follow="handleFollowRecommendation" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { UserAdd } from '@element-plus/icons-vue'
import FollowingList from "@/components/personalCenter/FollowingList.vue";
import RecommendationList from "@/components/personalCenter/RecommendationList.vue";

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const activeTab = ref('all')
const currentPage = ref(1)
const pageSize = ref(20)
const showRecommendation = ref(false)

// 模拟关注数据
const following = ref([
  {
    id: 1,
    username: '前端开发实验室',
    avatar: 'https://example.com/avatar1.jpg',
    description: '分享前端开发技术和实战经验',
    isMutual: true,
    isSpecial: true,
    fansCount: 125000,
    videoCount: 230,
    followTime: '2024-01-10T14:30:00Z'
  },
  {
    id: 2,
    username: 'UI设计之家',
    avatar: 'https://example.com/avatar2.jpg',
    description: '专注UI/UX设计分享和技巧',
    isMutual: false,
    isSpecial: false,
    fansCount: 89000,
    videoCount: 150,
    followTime: '2024-01-12T09:15:00Z'
  }
])

// 计算属性
const filteredFollowing = computed(() => {
  let result = [...following.value]

  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(user =>
        user.username.toLowerCase().includes(keyword) ||
        user.description.toLowerCase().includes(keyword)
    )
  }

  return result
})

const mutualFollowing = computed(() => {
  return filteredFollowing.value.filter(user => user.isMutual)
})

const specialFollowing = computed(() => {
  return filteredFollowing.value.filter(user => user.isSpecial)
})
// 方法
const loadFollowing = async () => {
  loading.value = true
  localStorage.getItem('satoken');
  try {
    const response = await request.get('/user/follow')
    
    if (response.status === 200 && response.data.code === 0) {
      // 处理返回的数据
      if (Array.isArray(response.data.data)) {
        following.value = response.data.data.map(item => ({
          id: item.id || item.userId,
          username: item.username || item.userName || '未知用户',
          avatar: item.avatar || item.avatarUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
          description: item.description || item.bio || '',
          isMutual: item.isMutual || false,
          isSpecial: item.isSpecial || false,
          fansCount: item.fansCount || item.followers || 0,
          videoCount: item.videoCount || item.videos || 0,
          followTime: item.followTime || item.createTime || new Date().toISOString()
        }))
      } else if (response.data.data) {
        // 如果返回的是单个对象，转换为数组
        following.value = [response.data.data]
      } else {
        following.value = []
      }
    } else {
      ElMessage.error(response.data.message || '加载关注列表失败')
      following.value = []
    }
  } catch (error) {
    console.error('加载关注列表失败:', error)
    ElMessage.error(error.response?.data?.message || '加载关注列表失败，请稍后重试')
    following.value = []
  } finally {
    loading.value = false
  }
}

const handleUnfollow = async (user) => {
  try {
    await ElMessageBox.confirm(
        `确定要取消关注 ${user.username} 吗？`,
        '取消关注',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const index = following.value.findIndex(u => u.id === user.id)
    if (index !== -1) {
      following.value.splice(index, 1)
      ElMessage.success(`已取消关注 ${user.username}`)
    }
  } catch (error) {
    // 用户点击取消
  }
}

const handleFollowRecommendation = (user) => {
  // 添加新关注
  following.value.unshift({
    ...user,
    followTime: new Date().toISOString(),
    isMutual: false,
    isSpecial: false
  })

  showRecommendation.value = false
  ElMessage.success(`已关注 ${user.username}`)
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

// 生命周期
onMounted(() => {
  loadFollowing()
})
</script>

<style scoped>
.following-page {
  padding: 20px;
  min-height: 600px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  color: #18191c;
  font-size: 24px;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-input {
  width: 200px;
}

.following-tabs {
  margin-bottom: 24px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .following-page {
    padding: 12px;
  }

  .page-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: space-between;
  }

  .search-input {
    width: 150px;
  }
}
</style>